#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "rightclick.h"
#include <QDateEdit>
#include <QMessageBox>
#include <QTextCharFormat>
#include <QSound>
#include <QTimer>
#include <QDebug>
#include "alertwindow.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    evnts = new EventsHandler();
    listEvHandler = new RightClick(evnts);
    // install event filter
    ui->calendarWidget->installEventFilter(listEvHandler);
    listEvHandler->setDate(ui->calendarWidget->selectedDate());

    ui->calendarWidget->setWeekdayTextFormat(Qt::Saturday, ui->calendarWidget->weekdayTextFormat(Qt::Monday));

    ColorDays();
    QTimer *timer = new QTimer();
    connect(timer, SIGNAL(timeout()), this, SLOT(Checker()));
    timer->start(1000);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_calendarWidget_clicked(QDate date)
{
    listEvHandler->setDate(date);
    ColorDays();
    //
}

void MainWindow::ColorDays()
{
    QTextCharFormat frmt;
    QBrush brush;
    QDateTime dates[1000];
    int n = evnts->GetAllDates(dates);
    brush.setColor(Qt::darkGray);
    frmt.setBackground(brush);
    ui->calendarWidget->setDateTextFormat(dates[n].date(),frmt);
    for (int i = 0; i < n; i++)
        ui->calendarWidget->setDateTextFormat(dates[i].date(),frmt);
}

void MainWindow::Checker()
{
    QDateTime alarmTime[1000];
    int n = evnts->GetAllAlarmTimes(alarmTime);
    for (int i = 0; i < n; i++)
    {
        //qDebug("Test: %d ", alarmTime[i].secsTo(QDateTime::currentDateTime()));
        QDateTime now = QDateTime::currentDateTime();
        //qDebug("for %d its %d", i, now.secsTo(alarmTime[i]));
        if (now.secsTo(alarmTime[i]) == 0)
        {
            AlertWindow *wind;
            wind = new AlertWindow();
            wind->DisplayAlert(evnts->GetEvent(alarmTime[i]));
            wind->show();
        }

    }
}
